<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0;
            padding: 20px;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .game-container {
            background: white;
            border-radius: 15px;
            padding: 5px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            max-width: 100%;
            width: 100%;
            text-align: center;
        }
        
        h1 {
            color: #333;
            margin-bottom: 20px;
            font-size: 2.5em;
        }
        
        .game-area {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 20px;
        }
        
        #gameCanvas {
            border: 3px solid #333;
            border-radius: 8px;
            background: #f0f0f0;
            max-width: 100%;
            height: auto;
        }
        
        .game-info {
            flex: 1;
            text-align: left;
        }
        
        .score-board {
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .score-board h3 {
            margin: 0 0 10px 0;
            color: #333;
        }
        
        .score-board p {
            margin: 5px 0;
            font-size: 18px;
            font-weight: bold;
        }
        
        .controls {
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .controls h3 {
            margin: 0 0 10px 0;
            color: #333;
        }
        
        .controls p {
            margin: 5px 0;
            font-size: 14px;
        }
        
        .game-buttons {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        button {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: #28a745;
            color: white;
        }
        
        .btn-primary:hover {
            background: #218838;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #545b62;
            transform: translateY(-2px);
        }
        
        @media (max-width: 768px) {
            .game-container {
                padding: 5px;
            }
            
            .game-area {
                flex-direction: column;
                align-items: center;
            }
            
            .game-info {
                width: 100%;
            }
            
            .score-board, .controls {
                padding: 8px;
                margin-bottom: 10px;
            }
            
            .controls p {
                font-size: 12px;
            }
            
            h1 {
                font-size: 1.8em;
                margin-bottom: 10px;
            }
            
            .mobile-controls {
                order: 2;
                margin-top: 10px;
                margin-bottom: 10px;
            }
            
            .game-info {
                order: 3;
            }
        }
        
        .mobile-controls {
            display: none;
            margin-top: 15px;
            margin-bottom: 15px;
        }
        
        .control-row {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin: 10px 0;
        }
        
        .control-btn {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            border: 2px solid #333;
            background: #28a745;
            color: white;
            font-size: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            user-select: none;
            transition: all 0.2s ease;
            -webkit-tap-highlight-color: transparent;
            touch-action: manipulation;
        }
        
        .control-btn:hover {
            background: #218838;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .control-btn:active, .control-btn.pressed {
            background: #1e7e34;
            transform: scale(0.95);
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        @media (max-width: 768px) {
            .mobile-controls {
                display: block;
                margin-top: 5px;
                margin-bottom: 5px;
            }
            
            .control-row {
                margin: 5px 0;
            }
            
            .control-btn {
                width: 50px;
                height: 50px;
                font-size: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1>🐍 贪吃蛇游戏</h1>
        
        <div class="game-area">
            <canvas id="gameCanvas" width="400" height="400"></canvas>
            
            <div class="mobile-controls">
                <div class="control-row">
                    <div class="control-btn" ontouchstart="handleTouch(event, 'up');" ontouchend="handleTouchEnd(event);" onmousedown="handleMouseDown(event, 'up');" onmouseup="handleMouseUp(event);" onmouseleave="handleMouseUp(event);">↑</div>
                </div>
                <div class="control-row">
                    <div class="control-btn" ontouchstart="handleTouch(event, 'left');" ontouchend="handleTouchEnd(event);" onmousedown="handleMouseDown(event, 'left');" onmouseup="handleMouseUp(event);" onmouseleave="handleMouseUp(event);">←</div>
                    <div class="control-btn" ontouchstart="handleTouch(event, 'down');" ontouchend="handleTouchEnd(event);" onmousedown="handleMouseDown(event, 'down');" onmouseup="handleMouseUp(event);" onmouseleave="handleMouseUp(event);">↓</div>
                    <div class="control-btn" ontouchstart="handleTouch(event, 'right');" ontouchend="handleTouchEnd(event);" onmousedown="handleMouseDown(event, 'right');" onmouseup="handleMouseUp(event);" onmouseleave="handleMouseUp(event);">→</div>
                </div>
            </div>
            
            <div class="game-info">
                <div class="game-buttons">
                    <button class="btn-primary" onclick="startGame()">开始游戏</button>
                    <button class="btn-secondary" onclick="pauseGame()">暂停游戏</button>
                    <button class="btn-secondary" onclick="resetGame()">重新开始</button>
                </div>
                
                <div class="score-board">
                    <h3>📊 游戏统计</h3>
                    <p>分数: <span id="score">0</span></p>
                    <p>长度: <span id="length">1</span></p>
                    <p>最高分: <span id="highScore">0</span></p>
                </div>
                
                <div class="controls">
                    <h3>🎯 操作说明</h3>
                    <p>↑ ↓ ← → : 控制方向</p>
                    <p>空格 : 暂停/继续</p>
                    <p>吃食物增长身体和分数</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
        // 游戏常量
        const GRID_SIZE = 20;
        const GRID_WIDTH = canvas.width / GRID_SIZE;
        const GRID_HEIGHT = canvas.height / GRID_SIZE;
        
        // 游戏状态
        let snake = [{x: 10, y: 10}];
        let direction = {x: 0, y: 0};
        let food = generateFood();
        let gameRunning = false;
        let gamePaused = false;
        let score = 0;
        let highScore = localStorage.getItem('snakeHighScore') || 0;
        let gameLoop;
        let touchInterval;
        
        // 初始化游戏
        function initGame() {
            snake = [{x: 10, y: 10}];
            direction = {x: 0, y: 0};
            food = generateFood();
            score = 0;
            gameRunning = false;
            gamePaused = false;
            updateScore();
            updateHighScore();
            drawGame();
        }
        
        // 生成食物
        function generateFood() {
            let newFood;
            do {
                newFood = {
                    x: Math.floor(Math.random() * GRID_WIDTH),
                    y: Math.floor(Math.random() * GRID_HEIGHT)
                };
            } while (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
            return newFood;
        }
        
        // 绘制游戏
        function drawGame() {
            // 清空画布
            ctx.fillStyle = '#f0f0f0';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制网格
            ctx.strokeStyle = '#ddd';
            ctx.lineWidth = 1;
            for (let i = 0; i <= GRID_WIDTH; i++) {
                ctx.beginPath();
                ctx.moveTo(i * GRID_SIZE, 0);
                ctx.lineTo(i * GRID_SIZE, canvas.height);
                ctx.stroke();
            }
            for (let i = 0; i <= GRID_HEIGHT; i++) {
                ctx.beginPath();
                ctx.moveTo(0, i * GRID_SIZE);
                ctx.lineTo(canvas.width, i * GRID_SIZE);
                ctx.stroke();
            }
            
            // 绘制蛇
            snake.forEach((segment, index) => {
                if (index === 0) {
                    // 蛇头
                    ctx.fillStyle = '#28a745';
                } else {
                    // 蛇身
                    ctx.fillStyle = '#34ce57';
                }
                ctx.fillRect(segment.x * GRID_SIZE, segment.y * GRID_SIZE, GRID_SIZE - 2, GRID_SIZE - 2);
                
                // 蛇头眼睛
                if (index === 0) {
                    ctx.fillStyle = 'white';
                    const eyeSize = 3;
                    const eyeOffset = 5;
                    
                    if (direction.x === 1) { // 向右
                        ctx.fillRect(segment.x * GRID_SIZE + GRID_SIZE - eyeOffset - eyeSize, segment.y * GRID_SIZE + eyeOffset, eyeSize, eyeSize);
                        ctx.fillRect(segment.x * GRID_SIZE + GRID_SIZE - eyeOffset - eyeSize, segment.y * GRID_SIZE + GRID_SIZE - eyeOffset - eyeSize, eyeSize, eyeSize);
                    } else if (direction.x === -1) { // 向左
                        ctx.fillRect(segment.x * GRID_SIZE + eyeOffset, segment.y * GRID_SIZE + eyeOffset, eyeSize, eyeSize);
                        ctx.fillRect(segment.x * GRID_SIZE + eyeOffset, segment.y * GRID_SIZE + GRID_SIZE - eyeOffset - eyeSize, eyeSize, eyeSize);
                    } else if (direction.y === -1) { // 向上
                        ctx.fillRect(segment.x * GRID_SIZE + eyeOffset, segment.y * GRID_SIZE + eyeOffset, eyeSize, eyeSize);
                        ctx.fillRect(segment.x * GRID_SIZE + GRID_SIZE - eyeOffset - eyeSize, segment.y * GRID_SIZE + eyeOffset, eyeSize, eyeSize);
                    } else if (direction.y === 1) { // 向下
                        ctx.fillRect(segment.x * GRID_SIZE + eyeOffset, segment.y * GRID_SIZE + GRID_SIZE - eyeOffset - eyeSize, eyeSize, eyeSize);
                        ctx.fillRect(segment.x * GRID_SIZE + GRID_SIZE - eyeOffset - eyeSize, segment.y * GRID_SIZE + GRID_SIZE - eyeOffset - eyeSize, eyeSize, eyeSize);
                    }
                }
            });
            
            // 绘制食物
            ctx.fillStyle = '#dc3545';
            ctx.beginPath();
            ctx.arc(food.x * GRID_SIZE + GRID_SIZE / 2, food.y * GRID_SIZE + GRID_SIZE / 2, GRID_SIZE / 2 - 2, 0, 2 * Math.PI);
            ctx.fill();
        }
        
        // 更新游戏状态
        function updateGame() {
            if (!gameRunning || gamePaused) return;
            
            // 移动蛇头
            const head = {x: snake[0].x + direction.x, y: snake[0].y + direction.y};
            
            // 检查碰撞
            if (head.x < 0 || head.x >= GRID_WIDTH || head.y < 0 || head.y >= GRID_HEIGHT ||
                snake.some(segment => segment.x === head.x && segment.y === head.y)) {
                gameOver();
                return;
            }
            
            snake.unshift(head);
            
            // 检查是否吃到食物
            if (head.x === food.x && head.y === food.y) {
                score += 10;
                updateScore();
                food = generateFood();
            } else {
                snake.pop();
            }
            
            updateLength();
            drawGame();
        }
        
        // 游戏结束
        function gameOver() {
            gameRunning = false;
            clearInterval(gameLoop);
            
            if (score > highScore) {
                highScore = score;
                localStorage.setItem('snakeHighScore', highScore);
                updateHighScore();
            }
            
            showMessage(`游戏结束！得分：${score}`);
        }
        
        // 开始游戏
        function startGame() {
            if (gameRunning) return;
            
            if (snake.length === 1 && direction.x === 0 && direction.y === 0) {
                direction = {x: 1, y: 0}; // 默认向右移动
            }
            
            gameRunning = true;
            gamePaused = false;
            gameLoop = setInterval(updateGame, 150);
        }
        
        // 暂停游戏
        function pauseGame() {
            if (!gameRunning) return;
            
            gamePaused = !gamePaused;
            if (gamePaused) {
                clearInterval(gameLoop);
                showMessage('游戏已暂停');
            } else {
                gameLoop = setInterval(updateGame, 150);
            }
        }
        
        // 重置游戏
        function resetGame() {
            clearInterval(gameLoop);
            initGame();
        }
        
        // 更新分数显示
        function updateScore() {
            document.getElementById('score').textContent = score;
        }
        
        // 更新长度显示
        function updateLength() {
            document.getElementById('length').textContent = snake.length;
        }
        
        // 更新最高分显示
        function updateHighScore() {
            document.getElementById('highScore').textContent = highScore;
        }
        
        // 显示消息
        function showMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.textContent = text;
            messageDiv.style.position = 'fixed';
            messageDiv.style.top = '50%';
            messageDiv.style.left = '50%';
            messageDiv.style.transform = 'translate(-50%, -50%)';
            messageDiv.style.background = 'rgba(0, 0, 0, 0.8)';
            messageDiv.style.color = 'white';
            messageDiv.style.padding = '20px';
            messageDiv.style.borderRadius = '10px';
            messageDiv.style.fontSize = '18px';
            messageDiv.style.zIndex = '1000';
            
            document.body.appendChild(messageDiv);
            
            setTimeout(() => {
                document.body.removeChild(messageDiv);
            }, 2000);
        }
        
        // 键盘控制
        document.addEventListener('keydown', (e) => {
            if (!gameRunning && e.key !== ' ') return;
            
            switch(e.key) {
                case 'ArrowUp':
                    if (direction.y === 0) {
                        direction = {x: 0, y: -1};
                    }
                    break;
                case 'ArrowDown':
                    if (direction.y === 0) {
                        direction = {x: 0, y: 1};
                    }
                    break;
                case 'ArrowLeft':
                    if (direction.x === 0) {
                        direction = {x: -1, y: 0};
                    }
                    break;
                case 'ArrowRight':
                    if (direction.x === 0) {
                        direction = {x: 1, y: 0};
                    }
                    break;
                case ' ':
                    pauseGame();
                    break;
            }
        });
        
        // 触摸控制
        function handleTouch(event, action) {
            event.preventDefault();
            
            if (!gameRunning) {
                showMessage('请先点击"开始游戏"按钮！');
                return;
            }
            
            if (gamePaused) {
                showMessage('游戏已暂停，请点击"暂停游戏"按钮继续！');
                return;
            }
            
            switch(action) {
                case 'up':
                    if (direction.y === 0) {
                        direction = {x: 0, y: -1};
                    }
                    break;
                case 'down':
                    if (direction.y === 0) {
                        direction = {x: 0, y: 1};
                    }
                    break;
                case 'left':
                    if (direction.x === 0) {
                        direction = {x: -1, y: 0};
                    }
                    break;
                case 'right':
                    if (direction.x === 0) {
                        direction = {x: 1, y: 0};
                    }
                    break;
            }
            
            // 长按连续移动
            touchInterval = setInterval(() => {
                switch(action) {
                    case 'up':
                        if (direction.y === 0) {
                            direction = {x: 0, y: -1};
                        }
                        break;
                    case 'down':
                        if (direction.y === 0) {
                            direction = {x: 0, y: 1};
                        }
                        break;
                    case 'left':
                        if (direction.x === 0) {
                            direction = {x: -1, y: 0};
                        }
                        break;
                    case 'right':
                        if (direction.x === 0) {
                            direction = {x: 1, y: 0};
                        }
                        break;
                }
            }, 150);
        }
        
        function handleTouchEnd(event) {
            event.preventDefault();
            if (touchInterval) {
                clearInterval(touchInterval);
                touchInterval = null;
            }
        }
        
        // 鼠标控制（桌面端兼容）
        function handleMouseDown(event, action) {
            event.preventDefault();
            const btn = event.target;
            btn.classList.add('pressed');
            handleTouch(event, action);
        }
        
        function handleMouseUp(event) {
            event.preventDefault();
            const btn = event.target;
            btn.classList.remove('pressed');
            handleTouchEnd(event);
        }
        
        // 初始化游戏
        window.addEventListener('load', initGame);
    </script>
</body>
</html>